package app

import (
	"github.com/go-apibox/api"
	"github.com/go-apibox/filter"
)

// 用户登录注销

func ActionUserLogin(c *api.Context) interface{} {
	params := c.NewParams()
	params.Add("UserName", filter.EmptyToNil(), filter.Required(), filter.String())
	params.Add("Password", filter.EmptyToNil(), filter.Required(), filter.String())
	if apiErr := params.Parse(); apiErr != nil {
		return apiErr
	}

	name := params.GetString("UserName")
	pw := params.GetString("Password")

	user := new(User)
	has, err := app.engine.Where("user_name = ?", name).Get(user)
	if err != nil {
		app.logger.Error(err)
		return c.Error.New(api.ErrorInternalError, "Connect db failed")
	}
	if !has {
		return c.Error.New(api.ErrorInvalidParam, "UserName")
	}

	if user.Status != USER_STATUS_NORMAL {
		return c.Error.New(api.ErrorInvalidParam, "User Status Error")
	}

	if !VerifyPW(pw, user.Password) {
		return c.Error.New(api.ErrorInvalidParam, "PW")
	}

	session, err := c.Session(SESSION_NAME)
	if err != nil {
		return c.Error.New(api.ErrorInternalError, "SessionFailed").SetMessage(err.Error())
	}

	// 标识用户已验证
	session.Values["authed"] = true
	session.Values["UserId"] = user.UserId
	session.Values["UserName"] = user.UserName
	session.Values["UserType"] = user.UserType
	session.Values["Status"] = user.Status
	session.Save()
	user.Password = ""
	return user
}

func ActionUserLogout(c *api.Context) interface{} {
	session, err := GetSession(c)
	if err != nil {
		return err
	}

	if err := session.session.Destroy(); err != nil {
		app.logger.Error(err)
	}

	app.logger.Debug("用户登出确认")
	return true
}
